package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.*;
import com.indusfo.spc.pojo.Datadict;
import com.indusfo.spc.pojo.Pro;
import com.indusfo.spc.pojo.ProStation;
import com.indusfo.spc.pojo.Station;
import com.indusfo.spc.service.ProService;
import com.indusfo.spc.vo.HintMessage;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/*
 * @author louk
 * @date 2019/11/18 14:37
 */
@Service
public class ProServiceImpl implements ProService {
    private static final Logger logger = LoggerFactory.getLogger(ProServiceImpl.class);

    @Resource
    private ProMapper proMapper;


    @Resource
    private ProStationMapper proStationMapper;


    @Resource
    private UploadMapper uploadMapper;

    @Resource
    private RepairDetailMapper repairDetailMapper;


    @Resource
    private DosingMapper dosingMapper;

    @Resource
    private ProfileDetailMapper profileDetailMapper;

    /**
     * 更新
     *
     * @param pro
     * @param staIds
     * @return
     */
    @Override
    public JSONObject updatePro(Pro pro, Integer[] staIds) {
        String vcRemark = "";
        if (pro.getRemark() == null) {
            pro.setRemark(vcRemark);
        }
        try {
            //更新id不能为空
            if (pro.getProId() == null) {
                throw new ParamsErrorException("请选择要更新的工序");
            }
            // 如果参数不合法，抛出参数异常
            checkParam(pro);
            // 调用存储过程
            int row = proMapper.updateByPrimaryKeySelective(pro);
            // 返回影响行数
            if (row == 0) {
                throw new ModifyFailedException("数据更新失败");
            }
            //通过工序ID获取所有的工位进行过滤
            List<ProStation> proStationByProId = proStationMapper.queryByProId(pro.getProId());
            if (staIds != null && staIds.length > 0) {


                //传递数组转集合
                List<Integer> arrayToList = new ArrayList<>();
                //数据库中删除的工位集合
                List<Integer> dataBaseList = new ArrayList<>();
                for (int i = 0; i < staIds.length; i++) {
                    arrayToList.add(staIds[i]);
                }
                //如果当前工序下存在工位,那么进行判断是新增还是删除,
                //如果更新的当前工序下存在工位
                if (proStationByProId != null && proStationByProId.size() > 0) {
                    for (ProStation proList : proStationByProId) {
                        //如果走到这里说明传递的工位数组为空说明当前列表当中已经把原先数据库存的工位都删除掉了
                        dataBaseList.add(proList.getStationId());
                    }

                    List<Integer> insertStationId = new ArrayList<>();
                    List<Integer> deleteStationId = new ArrayList<>();
                    //当数据库的工位列表中不包含前端传过来的工位id
                    for (Integer insertStaId : arrayToList) {
                        if (!dataBaseList.contains(insertStaId)) {
                            insertStationId.add(insertStaId);
                        }
                    }
                    for (Integer deleteStaId : dataBaseList) {
                        if (!arrayToList.contains(deleteStaId)) {
                            deleteStationId.add(deleteStaId);
                        }
                    }
                    if (!insertStationId.isEmpty()) {
                        proStationMapper.insertProStation(pro.getProId(), insertStationId, 1);
                    }
                    if (!deleteStationId.isEmpty()) {
                        proStationMapper.defineProList(pro.getProId(), deleteStationId, 2);
                    }

                } else {
                    //如果不存在直接进行新增
                    //新增工位
                    proStationMapper.insertProStation(pro.getProId(), arrayToList, 1);
                }
            } else {
                if (!proStationByProId.isEmpty()) {
                    List<Integer> updateProStationList = new ArrayList<>();
                    for (ProStation proList : proStationByProId) {
                        //如果走到这里说明传递的工位数组为空说明当前列表当中已经把原先数据库存的工位都删除掉了
                        updateProStationList.add(proList.getStationId());
                    }

                    proStationMapper.defineProList(pro.getProId(), updateProStationList, 2);

                }
            }
            return JSONObject.oK("更新成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 新增
     *
     * @param pro
     * @param staIds
     * @return
     */
    @Transactional
    @Override
    public JSONObject insertPro(Pro pro, Integer[] staIds) {

        try {
            //新增时不能有工序id
            if (pro.getProId() != null) {
                throw new ParamsErrorException("新增工序，不能有工序id");
            }
            // 如果参数不合法，抛出参数异常
            checkParam(pro);
            // 调用存储过程
            int row = proMapper.insertSelective(pro);
            if (row == 0) {
                throw new ModifyFailedException("新增工序失败");
            }
            List<Pro> pros = proMapper.listPros(pro);
            if (pros != null && staIds != null && staIds.length > 0) {
                List<Integer> stationIdList = new ArrayList<>();
                for (Integer staId : staIds) {
                    stationIdList.add(staId);
                }
                int flag = proStationMapper.insertProStation(pros.get(0).getProId(), stationIdList, 1);
                if (flag == 0) {
                    throw new ModifyFailedException("新增工位失败");
                }
            }
            return JSONObject.oK("新增成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 工序查询
     *
     * @param pro
     * @return com.indusfo.spc.vo.JSONObject
     * @author xuz
     * @date 2018/11/23 1:55 PM
     */

    @Override
    public JSONObject queryPro(Pro pro) {
        List<Pro> listPro = null;
        try {
            Integer pagesize = pro.getPagesize();
            Integer pageindex = pro.getPageindex();
            if (pagesize != null && pageindex != null) {
                pro.setIncept(pagesize * (pageindex - 1));
            }
            Integer lProId = pro.getProId();
            if (lProId != null) {
                //如果有工序id,则查询单个工序信息
                listPro = proMapper.getPro(lProId);
            } else {
                //查询多个
                listPro = proMapper.listPros(pro);
            }
            if (listPro.isEmpty()) {
                return JSONObject.oK("没有工序相关数据", listPro, 0);
            }
            //查询分页总数
            int count = proMapper.countPro(pro);
            return JSONObject.oK("查询成功", listPro, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 工序状态修改
     *
     * @param lProIds, lDataState
     * @return com.indusfo.spc.vo.JSONObject
     * @author xuz
     * @date 2018/11/23 1:55 PM
     */
    @Transactional
    @Override
    public JSONObject deletePro(Long[] lProIds, Integer lDataState) {
        try {
            if (lDataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            } else if (lDataState != 1 && lDataState != 2 && lDataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (lProIds == null || lProIds.length == 0) {
                throw new ParamsErrorException("请选择工序");
            }
            if (new Integer(2).equals(lDataState)) {
                JSONObject jsonResult = checkStation(lProIds);
                if (!(Boolean) jsonResult.getData()) {
                    return jsonResult;
                }
            }

            // 执行存储过程
            int row = proMapper.deltePro(lProIds, lDataState);
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (lDataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch (lDataState) {
                    case 1:
                        msg = "启用成功";
                        break;
                    case 2:
                        msg = "删除成功";
                        break;
                    case 3:
                        msg = "停用成功";
                        break;
                    default:
                }
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }

    }

    /***
     * 工序查询  排除数组中的数据
     *
     */
    @Override
    public JSONObject queryProIds(Pro pro, Long[] proIds) {
        List<Pro> listPro = null;
        try {
            Integer pagesize = pro.getPagesize();
            Integer pageindex = pro.getPageindex();
            if (pagesize != null && pageindex != null) {
                pro.setIncept(pagesize * (pageindex - 1));
            }
            if (proIds == null) {
            } else if (proIds.length == 0) {
                proIds = null;
            }
            pro.setDataState(1);
            listPro = proMapper.listProIds(pro, proIds);
            if (listPro.isEmpty()) {
                return JSONObject.oK("没有工序相关数据", listPro, 0);
            }
            //查询分页总数
            int count = proMapper.countProIds(pro, proIds);
            return JSONObject.oK("查询成功", listPro, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 通过不良现象id查询工序集合
     *
     * @param pro
     * @param badphenoId
     * @return
     */
    @Override
    public JSONObject queryBadPhenoProList(Pro pro, Integer badphenoId) {
        List<Pro> listPro = new ArrayList<>();
        if (badphenoId == null || "".equals(badphenoId)) {
            return JSONObject.oK("查询成功", listPro, null);
        }
        try {
            Integer pagesize = pro.getPagesize();
            Integer pageindex = pro.getPageindex();
            if (pagesize != null && pageindex != null) {
                pro.setIncept(pagesize * (pageindex - 1));
            }
            listPro = proMapper.queryBadPhenoProList(pro, badphenoId);
            if (listPro.isEmpty()) {
                return JSONObject.oK("没有工序相关数据", listPro, 0);
            }
            //查询分页总数
            int count = proMapper.countBadPhenoProList(pro, badphenoId);
            return JSONObject.oK("查询成功", listPro, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }

    }

    /**
     * 查询指定工序下的工位
     *
     * @param lProIds
     * @return
     */
    @Override
    public JSONObject checkStation(Long[] lProIds) {
        if (lProIds != null && lProIds.length > 0) {
            // 工序 下面有工位 不能删除
            int useProStation = proStationMapper.queryByProIds(lProIds);
            if(useProStation>0){
                return JSONObject.build(JSONObject.ERROR, "工序下包含工位,无法删除",false);
            }
            //工序 被维修工序段使用过 不能删除
            int useProRepairDetail=repairDetailMapper.queryUserPro(lProIds);
            if(useProRepairDetail>0){
                return JSONObject.build(JSONObject.ERROR, "工序已被维修工序段使用,无法删除",false);
            }

            //工序 被叫料信息使用过  不能删除
            int useProDosing=dosingMapper.queryUsePro(lProIds);
            if(useProDosing>0){
                return JSONObject.build(JSONObject.ERROR, "工序已被叫料信息使用,无法删除",false);
            }
            //工序 被工艺文件库使用过  不能删除
            int useProfileDetail=profileDetailMapper.queryUsePro(lProIds);
            if(useProfileDetail>0){
                return JSONObject.build(JSONObject.ERROR, "工序已被工艺文件库使用,无法删除",false);
            }
        }
        return JSONObject.build(JSONObject.SUCCESS, "判定完成", true);
    }

    /**
     * 检查excel字段
     *
     * @param pro
     * @return
     */
    @Override
    public String checkNoRepeat(Pro pro) {
        //工序名称
        String vcProName = pro.getProName();
        //工序类型名称
        String vcItemName = pro.getProTypeName();
        if (StringUtils.isBlank(vcProName) && StringUtils.isBlank(vcItemName) && StringUtils.isBlank(pro.getRemark())) {
            return "该行数据为空(原因:清空行内容时未清空彻底/未输入)";
        }
        if (StringUtils.isBlank(vcProName)) {
            return "工序名称为空";
        }
        if (pro.getProName().length() > 50) {
            return "工序名称超过规定长度50";
        }
        if (!StringUtils.isEmpty(pro.getRemark()) && pro.getRemark().getBytes().length > 50) {
            return "说明超过规定长度50";
        }
        // 校验工序名不能重复
        Integer proCounts = proMapper.selectPros(pro);
        if (proCounts != 0) {
            return "该工序名已存在";
        }
        Map<String, Datadict> tdatadictMap = uploadMapper.queryType(101031);
        if (!tdatadictMap.containsKey(vcItemName)) {
            return "工序类型填写不规范/错误";
        }
        Datadict tdatadict = tdatadictMap.get(vcItemName);
        pro.setProTypeName(String.valueOf(tdatadict.getItemId()));
        return null;
    }

    /**
     * 批量新增工序
     *
     * @param proList
     * @return
     */
    @Override
    public JSONObject updateListPro(List<Pro> proList) {
//        uploadMapper.updateListPro(proList);
        return null;
    }


    /*
     * 参数校验
     *
     * @author xuz
     * @date 2018/11/29 2:36 PM
     * @param pro, vcRemark]
     * @return void

     */
    private void checkParam(Pro pro) {

        if (StringUtils.isEmpty(pro.getProName())) {
            throw new ParamsErrorException("工序名不能为空");
        }
        if (pro.getProName().length() > 50) {
            throw new ParamsErrorException("工序名称超过规定长度50");
        }
        if (!StringUtils.isEmpty(pro.getRemark()) && pro.getRemark().getBytes().length > 50) {
            throw new ParamsErrorException("说明超过规定长度50");
        }
        if (pro.getProTypeId() == null || pro.getProTypeId().length() == 0) {
            throw new ParamsErrorException("选择工序类型");
        }
        // 校验工序名不能重复
        Integer proCounts = proMapper.selectPros(pro);
        if (proCounts != 0) {
            throw new ParamsErrorException("该工序名已存在");
        }
    }

    /**
     * 去添加查询（产品，任务单，批次）
     */
    @Override
    public JSONObject queryListProToInsert(Pro pro) {
        try {
            //获取页面的数据个数
            Integer pagesize = pro.getPagesize();
            //获取查询的页数
            Integer pageindex = pro.getPageindex();
            if (pagesize != null && pageindex != null) {
                pro.setIncept(pagesize * (pageindex - 1));
            }
            //执行查询操作
            List<Pro> proList = proMapper.queryListProToInsert(pro);

            //如果页数和页面数量都不为空的情况下进行计数
            if (proList.isEmpty()) {
                return JSONObject.oK(HintMessage.QUERY_NULL, proList, 0);
            } else {
                Integer count = proMapper.countProToInsert(pro);
                return JSONObject.oK(HintMessage.QUERY_SUCCESS, proList, count);
            }

        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());

        }
    }
}
